﻿// DataFetcher.cs
using System;
using System.Collections.Concurrent;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq; // 需要安装 Newtonsoft.Json NuGet包

namespace ExcelCOMAddin
{
 
    [ComVisible(true)]
    [Guid("42424332-9D6D-40E7-B449-A4A442354925")]// 替换为实际GUID
    [ProgId("EastMoneyDataFetcher.DataFetcher")]
    public class DataFetcher
    {
        private static readonly HttpClient _httpClient = CreateHttpClient();
        private static readonly ConcurrentDictionary<string, (object Value, DateTime Timestamp)> _cache = new();
        private const int CacheDurationInSeconds = 300; // 缓存5分钟

        // 创建HTTP客户端
        private static HttpClient CreateHttpClient()
        {
            var handler = new HttpClientHandler
            {
                AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
            };

            // 设置ServicePointManager的连接限制（全局设置）
            // 注意：这会影响整个应用程序域，不推荐在生产环境中全局修改
            // System.Net.ServicePointManager.DefaultConnectionLimit = Environment.ProcessorCount * 4;

            return new HttpClient(handler)
            {
                Timeout = TimeSpan.FromSeconds(10),
                // MaxConnectionsPerServer 在 .NET Framework 的 HttpClientHandler 中不可用
                // 可以通过 ServicePointManager 进行全局设置
            };
        }

        // 异步获取数据
        public async Task<string> GetDataAsync(string symbol, string field)
        {
            try
            {
                string cacheKey = $"{symbol}_{field}";
                if (_cache.TryGetValue(cacheKey, out var cached) &&
                    (DateTime.Now - cached.Timestamp).TotalSeconds <= CacheDurationInSeconds)
                {
                    return cached.Value.ToString();
                }

                string url = $"https://push2.eastmoney.com/api/qt/clist/get?np=1&fltt=1&invt=2&fs=m%3A90%2Bt%3A2&fields=f14%2Cf12%2Cf13%2Cf62%2Cf204%2Cf205%2Cf206&fid=f62&pn=1&pz=5&po=1&ut=fa5fd1943c7b386f172d6893dbfba10b&dect=1&wbp2u=1794097457367022%7C0%7C1%7C0%7Cweb&_=1745892478165";
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string json = await response.Content.ReadAsStringAsync();

                // 解析JSON
                var data = JObject.Parse(json);
                object value = ParseJson(data, field);

                // 更新缓存
                _cache[cacheKey] = (value, DateTime.Now);

                return value.ToString();
            }
            catch (Exception ex)
            {
                return $"Error: {ex.Message}";
            }
        }

        // 同步方法供VBA调用
        public string GetData(string symbol, string field)
        {
            try
            {
                return Task.Run(() => GetDataAsync(symbol, field)).Result;
            }
            catch (AggregateException ae)
            {
                return $"Error: {ae.InnerException?.Message ?? "Unknown error"}";
            }
        }

        // JSON解析方法
        private object ParseJson(JObject json, string field)
        {
            try
            {
                return field switch
                {
                    "svr" => json["svr"]?.Value<decimal?>() ?? 0m,
                    "volume" => json["volume"]?.Value<long?>() ?? 0L,
                    "amount" => json["amount"]?.Value<decimal?>() ?? 0m,
                    "open" => json["open"]?.Value<decimal?>() ?? 0m,
                    "close" => json["close"]?.Value<decimal?>() ?? 0m,
                    _ => null
                };
            }
            catch
            {
                return null;
            }
        }
    }

    // 注意：GetValueOrDefault 不是 ConcurrentDictionary 的内置方法，我们不需要它
    // 如果需要，可以创建扩展方法，但在本例中不需要
}